package com.xayy.core.config.datasource;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 数据源切换AOP
 *
 * @author dongxingli
 * createTime 2021/2/25
 * @version V1.0
 */
@Component
@Aspect
@Order(-100)
@Slf4j
public class DatasourceAspect {

    @Pointcut("@annotation(com.xayy.core.config.datasource.DatasourceSelector)")
    private void change() {
    }

    @Before("change()")
    public void before(JoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        DatasourceSelector annotation = methodSignature.getMethod().getAnnotation(DatasourceSelector.class);
        String name = annotation.sourceName();
        DatasourceHolder.changeSource(name);
    }

    @After("change()")
    public void after() {
        DatasourceHolder.clearSource();
    }
}
